package swing.hibernate.JFrame;

import java.awt.EventQueue;

import javax.imageio.ImageIO;
import javax.swing.JInternalFrame;
import javax.swing.JScrollPane;

import java.awt.BorderLayout;

import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;

import dao.ConvertImage;
import dao.HashPassword;
import dao.TaiKhoanDAO;
import entities.TaiKhoan;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.TextEvent;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class JInternalFrameListAccount extends JInternalFrame {
	private JTable table;
	private JTextField textFieldUsername;
	private JPasswordField passwordField;
	private JTextField textFieldHoTen;
	private JTextField textFieldEmail;
	private JTextField textFieldDienThoai;
	private JTextField textFieldCongTy;
	private JTextField textFieldDiaChi;
	private JTextField imageURL;
	private TaiKhoanDAO tkDAO = new TaiKhoanDAO();
	private TaiKhoan tk;
	private JLabel lblAvatar;

	/**
	 * Create the frame.
	 */
	public JInternalFrameListAccount() {
		setClosable(true);
		setBounds(100, 100, 633, 471);
		setTitle("List Account");
		getContentPane().setLayout(null);

		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(10, 11, 601, 107);

		table = new JTable();
		table.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				String username = table.getValueAt(table.getSelectedRow(), 0)
						.toString();
				fillInformationToForm(username);

			}
		});
		table.setBounds(224, 150, 133, 84);
		scrollPane.setViewportView(table);
		getContentPane().add(scrollPane);

		JPanel panel = new JPanel();
		panel.setLayout(null);
		panel.setBorder(new TitledBorder(null, "Information Account",
				TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panel.setBounds(10, 129, 377, 306);
		getContentPane().add(panel);

		JLabel label = new JLabel("Username");
		label.setBounds(24, 25, 86, 14);
		panel.add(label);

		textFieldUsername = new JTextField();
		textFieldUsername.setColumns(10);
		textFieldUsername.setBounds(121, 22, 229, 20);
		panel.add(textFieldUsername);

		JLabel label_1 = new JLabel("Password");
		label_1.setBounds(24, 56, 86, 14);
		panel.add(label_1);

		passwordField = new JPasswordField();
		passwordField.setBounds(121, 53, 229, 20);
		panel.add(passwordField);

		JLabel label_2 = new JLabel("Họ Tên");
		label_2.setBounds(24, 87, 86, 14);
		panel.add(label_2);

		textFieldHoTen = new JTextField();
		textFieldHoTen.setColumns(10);
		textFieldHoTen.setBounds(121, 84, 229, 20);
		panel.add(textFieldHoTen);

		JLabel label_3 = new JLabel("Email");
		label_3.setBounds(24, 122, 86, 14);
		panel.add(label_3);

		textFieldEmail = new JTextField();
		textFieldEmail.setColumns(10);
		textFieldEmail.setBounds(121, 119, 229, 20);
		panel.add(textFieldEmail);

		JLabel label_4 = new JLabel("Điện Thoại");
		label_4.setBounds(24, 150, 86, 14);
		panel.add(label_4);

		textFieldDienThoai = new JTextField();
		textFieldDienThoai.setColumns(10);
		textFieldDienThoai.setBounds(121, 147, 229, 20);
		panel.add(textFieldDienThoai);

		JLabel label_5 = new JLabel("Công Ty");
		label_5.setBounds(24, 180, 86, 14);
		panel.add(label_5);

		textFieldCongTy = new JTextField();
		textFieldCongTy.setColumns(10);
		textFieldCongTy.setBounds(121, 177, 229, 20);
		panel.add(textFieldCongTy);

		JLabel label_6 = new JLabel("Địa Chỉ");
		label_6.setBounds(24, 208, 87, 14);
		panel.add(label_6);

		textFieldDiaChi = new JTextField();
		textFieldDiaChi.setColumns(10);
		textFieldDiaChi.setBounds(121, 205, 229, 20);
		panel.add(textFieldDiaChi);

		JButton btnUpdate = new JButton("Update");
		btnUpdate.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				updateAccount();
			}
		});
		btnUpdate.setBounds(122, 272, 89, 23);
		panel.add(btnUpdate);

		JButton btnDelete = new JButton("Delete");
		btnDelete.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int cf = JOptionPane.showConfirmDialog(null, "Are you sure ?",
						"Delete Account", JOptionPane.YES_NO_OPTION);
				if (cf == JOptionPane.YES_OPTION) {
					String username = table.getValueAt(table.getSelectedRow(),
							0).toString();
					tk = tkDAO.getAccount(username);
					if (tkDAO.delete(tk)) {
						JOptionPane.showMessageDialog(null, "Delete Success");
						loadData();
					} else {
						JOptionPane.showMessageDialog(null, "Delete Fail");
					}

				}
			}
		});
		btnDelete.setBounds(221, 272, 89, 23);
		panel.add(btnDelete);

		JPanel panel_1 = new JPanel();
		panel_1.setBorder(new TitledBorder(null, "Avatar",
				TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panel_1.setBounds(397, 129, 214, 301);
		getContentPane().add(panel_1);
		panel_1.setLayout(null);

		lblAvatar = new JLabel("");
		lblAvatar.setBounds(10, 21, 195, 206);
		panel_1.add(lblAvatar);

		imageURL = new JTextField();
		imageURL.setBounds(10, 238, 195, 22);
		panel_1.add(imageURL);
		imageURL.setColumns(10);

		JButton btnOpenAvatar = new JButton("Open");
		btnOpenAvatar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JFileChooser chooser = new JFileChooser();
				chooser.setDialogTitle("Update Avatar");
				chooser.showOpenDialog(null);
				if (chooser.getSelectedFile() != null) {
					imageURL.setText(chooser.getSelectedFile()
							.getAbsolutePath());
				}
			}
		});
		btnOpenAvatar.setBounds(10, 272, 89, 23);
		panel_1.add(btnOpenAvatar);

		JButton btnReview = new JButton("Review");
		btnReview.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if (!imageURL.getText().equals("")) {
					try {
						byte[] res = ConvertImage
								.convertImageToByteArray(imageURL.getText());
						BufferedImage image;
						image = ImageIO.read(new ByteArrayInputStream(res));
						setAvatarToLabel(lblAvatar, image);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		});
		btnReview.setBounds(108, 272, 97, 23);
		panel_1.add(btnReview);
		loadData();
	}

	private void updateAccount() {
		// TODO Auto-generated method stub
		String username = table.getValueAt(table.getSelectedRow(), 0)
				.toString();

		tk = tkDAO.getAccount(username);
		if (checkEmpty() == false) {
			JOptionPane.showMessageDialog(null,
					"Please Insert Full Information");
		} else {
			String password = passwordField.getPassword().toString();
			String hashpassword = HashPassword.MD5(password);
			tk.setPassword(hashpassword);
			tk.setHoten(textFieldHoTen.getText());
			tk.setEmail(textFieldEmail.getText());
			tk.setDienthoai(Integer.parseInt(textFieldDienThoai.getText()));
			tk.setCongty(textFieldCongTy.getText());
			tk.setDiachi(textFieldDiaChi.getText());
			String urlImage = imageURL.getText();
			if (!urlImage.equals("")) {
				byte[] res = ConvertImage.convertImageToByteArray(urlImage);
				tk.setAvatar(res);
			}
			
			if (tkDAO.update(tk)) {
				JOptionPane.showMessageDialog(null, "Update Success");
				loadData();
			} else {
				JOptionPane.showMessageDialog(null, "Update Fail");
			}
		}

	}

	private void loadData() {
		// TODO Auto-generated method stub
		DefaultTableModel model = new DefaultTableModel();
		model.addColumn("Username");
		model.addColumn("Họ Tên");
		model.addColumn("Email");
		model.addColumn("Điện Thoại");

		TaiKhoanDAO tkDAO = new TaiKhoanDAO();

		for (TaiKhoan tk : tkDAO.listAccount()) {
			model.addRow(new Object[] { tk.getUsername(), tk.getHoten(),
					tk.getEmail(), tk.getDienthoai() });
		}
		table.setModel(model);
		table.repaint();
		table.revalidate();
	}

	private void fillInformationToForm(String username) {
		textFieldUsername.setText(username);
		textFieldUsername.setEditable(false);

		tk = tkDAO.getAccount(username);
		passwordField.setText(tk.getPassword());
		textFieldHoTen.setText(tk.getHoten());
		textFieldEmail.setText(tk.getEmail());
		textFieldDienThoai.setText(tk.getDienthoai() + "");
		textFieldCongTy.setText(tk.getCongty());
		textFieldDiaChi.setText(tk.getDiachi());

		try {
			BufferedImage image = ImageIO.read(new ByteArrayInputStream(tk
					.getAvatar()));
			setAvatarToLabel(lblAvatar, image);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void setAvatarToLabel(JLabel lblAvatar, BufferedImage image) {
		// TODO Auto-generated method stub
		int x = lblAvatar.getSize().width;
		int y = lblAvatar.getSize().height;

		int ix = image.getWidth();
		int iy = image.getHeight();

		int dx = 0;
		int dy = 0;

		if (x / y > ix / iy) {
			dy = y;
			dx = dy * ix / iy;
		} else {
			dx = x;
			dy = dx * iy / ix;
		}

		ImageIcon icon = new ImageIcon(image.getScaledInstance(dx, dy,
				image.SCALE_SMOOTH));
		lblAvatar.setIcon(icon);
	}

	private boolean checkEmpty() {
		if (passwordField.getPassword().toString().equals("")
				|| textFieldHoTen.getText().equals("")
				|| textFieldEmail.getText().equals("")
				|| textFieldDienThoai.getText().equals("")
				|| textFieldCongTy.getText().equals("")
				|| textFieldDiaChi.getText().equals("")){
			return false;
		} else {
			return true;
		}

	}
}
